import { Checkbox, Divider, message, Modal, Spin, Upload } from "antd";
import { forwardRef, useEffect, useImperativeHandle, useMemo, useState } from "react"
import { InboxOutlined } from '@ant-design/icons';
import { importTemplate } from '@/api/system/user'
import { download } from "@/utils";
import { useUserToken } from "@/store/userStore";

const ImportExcelModal = forwardRef(({ onOk }, ref) => {
  const [uploadData, setUploadData] = useState({
    // 是否显示弹出层（用户导入）
    uploadStatus: '',
    fileList: [],
    // 是否禁用上传
    isUploading: false,
    // 是否更新已经存在的用户数据
    updateSupport: 0,
    // 设置上传的请求头部
    // headers: { Authorization: 'Bearer ' + storage.get(ACCESS_TOKEN) },
    // 上传的地址
    url: import.meta.env.VITE_APP_BASE_API + '/system/user/importData'
  })
  const [isModalOpen, setIsModalOpen] = useState()
  const ACCESS_TOKEN = useUserToken()

  useEffect(() => {
    setUploadData({
      ...uploadData,
      headers: { Authorization: 'Bearer ' + ACCESS_TOKEN }
    })
  }, [ACCESS_TOKEN])

  useImperativeHandle(ref, () => ({
    showModal: () => {
      setIsModalOpen(true)
    },
  }));

  const handleCancel = () => {
    setIsModalOpen(false)
  };
  const downLoadTemplate = () => {
    importTemplate().then(res => {
      download(res.msg)
    })
  }

  const uploadChange = (info) => {
    let status = info.file.status
    const response = info.file.response
    if (response) {
      if (response.code === 200) {
        status = 'done'
      } else {
        status = 'error'
      }
    }

    if (status === 'done') {
      message.success(`${info.file.name}: 上传成功`)
      setIsModalOpen(true)
    } else if (status === 'error') {
      message.error(`${info.file.name}: ${info.file.response.msg}`)
    }
    setUploadData({
      ...uploadData,
      uploadStatus: status,
      fileList: []
    })
    onOk()
  }

  return <Modal title='导入用户' open={isModalOpen} placement="right"
    onCancel={handleCancel} onOk={handleCancel}>
    <Spin spinning={uploadData.uploadStatus === 'uploading'} tip="上传中...">
      <Upload.Dragger
        name={'file'}
        accept={".xlsx, .xls"}
        file-list={uploadData.fileList}
        multiple={false}
        headers={uploadData.headers}
        action={uploadData.url + '?updateSupport=' + uploadData.updateSupport}
        onChange={uploadChange}
      >
        <p className="ant-upload-drag-icon">
          <InboxOutlined />
        </p>
        <p className="ant-upload-text">请将文件拖拽到此处上传❥(^_-)</p>
        <p className="ant-upload-hint">支持单个上传，也可以点击后选择文件上传</p>
      </Upload.Dragger>
    </Spin>
    <div style={{ marginTop: '10px' }}>
      <Checkbox
        onChange={() => {
          setUploadData({ ...uploadData, updateSupport: !uploadData.updateSupport })
        }}
        checked={uploadData.updateSupport} >是否更新已经存在的用户数据</Checkbox>
      <a onClick={downLoadTemplate}>下载模板</a>
    </div>
  </Modal>
})

export default ImportExcelModal